package com.erd.datacollect.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

public class JsonTool {
  public static ObjectMapper defaultMapper(){
    return defaultMapper("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
  }
  public static ObjectMapper defaultMapper(String dateFormat){
    ObjectMapper mapper = new ObjectMapper();
    //在反序列化时忽略在 json 中存在但 Java 对象不存在的属性
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //如果是空对象的时候,不抛异常
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    //属性为null不转换
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    //在序列化时日期格式默认为 yyyy-MM-dd'T'HH:mm:ss.SSSZ
    // mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    //在序列化时自定义时间日期格式
    if(dateFormat!=null){
      mapper.setDateFormat(new SimpleDateFormat(dateFormat));
    }
    //在序列化时忽略值为 null 的属性
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    //在序列化时忽略值为默认值的属性,会跳过字符串""的属性
    //mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
    return mapper;
  }
  public static String toJson(Object obj)throws JsonProcessingException {
    ObjectMapper mapper = defaultMapper();
    return mapper.writeValueAsString(obj);
  }
  public static <T> T toObj(String jsonStr, TypeReference t)throws JsonProcessingException{
    ObjectMapper mapper = defaultMapper();
    return (T)mapper.readValue(jsonStr,t);
  }
  public static String toJson(Object obj,String dateFormat)throws JsonProcessingException {
    ObjectMapper mapper = defaultMapper(dateFormat);
    return mapper.writeValueAsString(obj);
  }
  public static <T> T toObj(String jsonStr, TypeReference t,String dateFormat)throws JsonProcessingException{
    ObjectMapper mapper = defaultMapper(dateFormat);
    return (T)mapper.readValue(jsonStr,t);
  }
}
